
#include "Connection.h"

Connection::Connection(EventLoop *loop, Socket *clientsock)
    : loop_(loop), clientsock_(clientsock)
{
    clientchannel_ = new Channel(loop_, clientsock->fd());
    clientchannel_->setreadcallback(std::bind(&Connection::onmessage, this));
    clientchannel_->setclosecallback(std::bind(&Connection::closecallback,this));
    clientchannel_->seterrorcallback(std::bind(&Connection::errorcallback,this));

    clientchannel_->setsendcallback(std::bind(&Connection::sendcallback,this));


    clientchannel_->enablereading();
    clientchannel_->useet(); // 设置边缘触发

    // printf(" hahaNew client connected: %s:%d\n", clientsock_->ip().c_str(), clientsock_->port());
}
Connection::~Connection()
{
    delete clientsock_;
    delete clientchannel_;
}
std::string Connection::ip()
{
    return clientsock_->ip();
}
uint16_t Connection::port()
{
    return clientsock_->port();
}

int Connection::fd() const
{
    return clientsock_->fd();
}

void Connection::closecallback()
{
    // printf("client(eventfd=%d) disconnected.\n", fd());
    // close(fd());
    closecallback_(this);
}
void Connection::errorcallback()
{
    // printf("else error\n");
    // close(fd());
    errorcallback_(this);
}

void Connection::setclosecallback(std::function<void(Connection*)> f)
{
    closecallback_ = f;
}
void Connection::seterrorcallback(std::function<void(Connection*)> f)
{
    errorcallback_ = f;
}

void Connection::sethaddlemsgcallback(std::function<void(Connection*,std::string)> f)
{
    haddlemsgcallback_ = f;
}

void Connection::onmessage()
{
    char buffer[1024];

    while (true)
    {                                   // 非阻塞IO循环读取
        bzero(&buffer, sizeof(buffer)); // 清空缓冲区

        ssize_t nread = read(fd(), buffer, sizeof(buffer));

        if (nread > 0)
        { // 成功读取数据
            printf("recv(eventfd=%d):%s\n", fd(), buffer);
            inputbuffer_.append(buffer,nread);

            // for (size_t i = 0; i < (size_t)nread; i++)
            // {
            //     buffer[i] = toupper(buffer[i]);
            // }

            // send(fd(), buffer, nread, 0); // 原样回发（使用nread而非strlen）
        }
        else if (nread == -1 && errno == EINTR)
        { // 被信号中断
            continue;
        }
        else if (nread == -1 && (errno == EAGAIN || errno == EWOULDBLOCK))
        { // 非阻塞无数据

            // outputbuffer_ = inputbuffer_;

            while (true)
            {
                int len = 0;

                memcpy(&len,inputbuffer_.data(),4);
                if(inputbuffer_.size()<4+len) break;

                std::string message(inputbuffer_.data()+4,len);
                inputbuffer_.erase(0,4+len);

                haddlemsgcallback_(this,message);

                // message = "replay:"+message;
                // len = message.size();

                // std::string tmpbuf((char*)&len,4);
                // tmpbuf.append(message);

                // write(fd(),tmpbuf.data(),tmpbuf.size());


            }
            



            //在这里调用数据处理函数
            //haddlemsgcallback_(this,message);
            // 暂时这样写
            // write(fd(),outputbuffer_.data(),outputbuffer_.size());
            // inputbuffer_.clear();
            // outputbuffer_.clear();

            break;
        }
        else if (nread == 0)
        { // 客户端断开连接
            // printf("client(eventfd=%d) disconnected.\n", fd_);
            // close(fd_);
            // closecallback_();
            closecallback();
            break;
        }
    }

}


void Connection::send(const char*data,int size )
{
    outputbuffer_.append(data,size);
    // 注册写事件
    clientchannel_->enablewriting();
}

 void Connection::sendcallback()
 {
    int write = ::write(fd(),outputbuffer_.data(),outputbuffer_.size()); // 尝试把outputbuffer中的数据全部发送出去
    if(write>0){
        outputbuffer_.erase(0,write);
    }

    if(outputbuffer_.size()==0){
        clientchannel_->disablewriting();
        sendcompletecallback_(this);
    }
 }


void Connection::setsendcompletecallback(std::function<void(Connection*)> f)
{
    sendcompletecallback_ = f;
}